#include "libwebsockets.h"
#include <string.h>
#include <pthread.h>
#include <stdio.h>
#include <iostream>

using namespace std;

struct lws * g_wsi = NULL;
pthread_mutex_t wsi_mutex = PTHREAD_MUTEX_INITIALIZER;

void* thread_function(void* arg) {
    printf("这是新线程在运行，参数是: %d\n", *(int*)arg);
    for (int i = 0; i < 100; i++)
    {
        sleep(1);
        cout << "i: " << i << endl;
        
        pthread_mutex_lock(&wsi_mutex);
        if (i == 20 && g_wsi != NULL)
        {
            string data = "run len is 120";
            unsigned char buf[LWS_PRE + 1024];
            memcpy(&buf[LWS_PRE], data.c_str(), data.size());
            lws_write(g_wsi, &buf[LWS_PRE], data.size(), LWS_WRITE_TEXT);
        }
        pthread_mutex_unlock(&wsi_mutex);
    }
    
    // 线程返回结果
    int * result = (int*)malloc(sizeof(int));
    *result = 123;
    return result;
}

// 协议回调函数
static int callback(struct lws *wsi, enum lws_callback_reasons reason,
                    void *user, void *in, size_t len) {
    switch (reason) {
        case LWS_CALLBACK_ESTABLISHED:
            printf("连接已建立\n");
            pthread_mutex_lock(&wsi_mutex);
            g_wsi = wsi;
            pthread_mutex_unlock(&wsi_mutex);
            break;
            
        case LWS_CALLBACK_CLOSED:
            printf("连接已关闭\n");
            pthread_mutex_lock(&wsi_mutex);
            if (g_wsi == wsi) {
                g_wsi = NULL; // 清理全局WSI指针
            }
            pthread_mutex_unlock(&wsi_mutex);
            break;
            
        case LWS_CALLBACK_RECEIVE:
            printf("收到消息: %.*s\n", (int)len, (char *)in);
            
            // 回显消息给客户端
            {
                unsigned char buf[LWS_PRE + 1024];
                memcpy(&buf[LWS_PRE], in, len);
                lws_write(wsi, &buf[LWS_PRE], len, LWS_WRITE_TEXT);
            }
            break;
            
        default:
            break;
    }
    return 0;
}

// 定义协议
static struct lws_protocols protocols[] = {
    {
        "echo-protocol",  // 协议名称
        callback,         // 回调函数
        0,                // 用户数据大小
        0,                // 接收缓冲区大小
    },
    {NULL, NULL, 0, 0} // 必须以NULL结尾
};

int main(int argc, char **argv) 
{
    pthread_t thread_id;
    int thread_arg = 42;
    void* thread_result;

    // 创建新线程
    int res = pthread_create(&thread_id, NULL, thread_function, &thread_arg);
    if (res != 0) {
        perror("线程创建失败");
        return 1;
    }

    struct lws_context_creation_info info;
    struct lws_context *context;
    
    // 初始化信息结构体
    memset(&info, 0, sizeof(info));
    info.port = 7681;             // 监听端口
    info.protocols = protocols;   // 注册协议
    info.gid = -1;                // 不改变进程组
    info.uid = -1;                // 不改变用户
    
    // 创建上下文
    context = lws_create_context(&info);
    if (context == NULL) {
        printf("创建libwebsockets上下文失败\n");
        return -1;
    }
    
    printf("WebSocket服务器已启动，端口: 7681\n");
    
    // 事件循环
    while (1) {
        lws_service(context, 50); // 每50ms处理一次事件
    }
    
    // 销毁上下文
    lws_context_destroy(context);

    // 等待新线程结束并获取返回值
    res = pthread_join(thread_id, &thread_result);
    if (res != 0) {
        perror("等待线程失败");
        return 1;
    }

    return 0;
}